import datetime
from itertools import chain
from django.http import JsonResponse
from django.utils import timezone
from django.views.generic import View
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework import viewsets

from user.models import User
from .models import Answer, InlineComment, Exam, ExamPaper
from .serializers import InlineCommentSerializer


class UpdateAnswerApi(View):

    def post(self, request):
        success = 1
        msg = 'saved'

        answer = Answer.objects.get(pk=request.POST.get("answer_id"))
        if 'content' in request.POST:
            present = timezone.now()
            start = answer.problem.start
            end = start + datetime.timedelta(
                minutes=answer.problem.minutes)
            # print(start, present, end)
            if start < present and present < end:
                answer.content = request.POST.get("content")
                answer.save()
            else:
                # invalid answer time
                success = 0
                msg = 'cannot update now'
        elif 'amendment' in request.POST:
            answer.amendment = request.POST.get('amendment')
            answer.save()

        data = {
            'success': success,
            'msg': msg,
        }

        return JsonResponse(data)


class InlineCommentListByAnswer(APIView):

    def dispatch(self, request, answer_id, format=None):
        return super(InlineCommentListByAnswer, self).dispatch(
            request, answer_id)

    def get(self, request, answer_id, format=None):
        answer = Answer.objects.get(pk=answer_id)
        comments = InlineComment.objects.filter(answer=answer)
        serializer = InlineCommentSerializer(comments, many=True)
        return Response(serializer.data)


class InlineCommentListByExam(APIView):

    def dispatch(self, request, exam_id, student_id, format=None):
        return super(InlineCommentListByExam, self).dispatch(
            request, exam_id, student_id)

    def get(self, request, exam_id, student_id, format=None):
        exam = Exam.objects.get(pk=exam_id)
        stu = User.objects.get(pk=student_id)
        qs = InlineComment.objects.none()
        for problem in exam.problems.all():
            exam_paper = ExamPaper.objects.get(exam=exam, student=stu)
            answer = Answer.objects.get(problem=problem, exam_paper=exam_paper)
            comments = InlineComment.objects.filter(
                answer=answer).order_by('-modified')
            print(comments)
            qs = list(chain(qs, comments))
        serializer = InlineCommentSerializer(qs, many=True)
        return Response(serializer.data)


class InlineCommentViewSet(viewsets.ModelViewSet):
    queryset = InlineComment.objects.all()
    serializer_class = InlineCommentSerializer

    def get_object(self):
        obj = super(InlineCommentViewSet, self).get_object()
        return obj

    def list(self, request, *args, **kwargs):
        print('list', args, kwargs)
        return super(InlineCommentViewSet, self).list(request, *args, **kwargs)

    def partial_update(self, request, pk=None):
        return super(InlineCommentViewSet, self).partial_update(request, pk)

    def create(self, request):
        print('create', request.POST)
        return super(InlineCommentViewSet, self).create(request)

    def retrieve(self, request, pk=None):
        print('retrieve')
        return super(InlineCommentViewSet, self).retrieve(request, pk)

    def update(self, request, *args, **kwargs):
        print('update', request.body, args, kwargs)
        return super(InlineCommentViewSet, self).update(
            request, *args, **kwargs)

    def destroy(self, request, pk=None):
        print('destroy')
        return super(InlineCommentViewSet, self).destroy(request, pk)
